﻿#region << 文 件 说 明 >>

/*----------------------------------------------------------------
// 文件名称：VampirewalDbBase
// 创 建 者：杨程
// 创建时间：2022/2/11 19:23:12
// 文件版本：V1.0.0
// ===============================================================
// 功能描述：
//
//
//----------------------------------------------------------------*/

#endregion

namespace Vampirewal.Core.Components;

/// <summary>
/// 数据库连接操作基类
/// <para>单机使用可直接继承这个基类使用，比较轻量极</para>
/// </summary>
public abstract class VampirewalCoreDataContext : IVampirewalCoreDataContext
{
    /// <summary>
    /// 构造函数
    /// </summary>
    public VampirewalCoreDataContext()
    {
        DbBaseOptions DbOptions = VampirewalCoreContext.GetInstance().GetService<IConfigContainer< DbBaseOptions>>().Value;

        var dbConnectConfigList = new List<ConnectionConfig>();

        foreach (var item in DbOptions.ConnectionStrings ?? new List<ConnectionString>())
        {
            string connStr = item.Value;

            if (item.DbType == DBTypeEnum.Sqlite)
            {
                var strs = connStr.Split('=');

                connStr = $"{strs[0]}={AppDomain.CurrentDomain.BaseDirectory}{strs[1]}";
            }

            dbConnectConfigList.Add(GetDbConnectionConfig(item.Key, connStr, item.DbType));
        }

        Client = new SqlSugarScope(dbConnectConfigList, db =>
        {
            foreach (var item in DbOptions.ConnectionStrings)
            {
                //SQL执行完
                db.GetConnection(item.Key).Aop.OnLogExecuted = OnLogExecuted;
                //SQL执行前
                db.GetConnection(item.Key).Aop.OnLogExecuting = OnLogExecuting;
                //SQL报错
                db.GetConnection(item.Key).Aop.OnError = OnError;
                //可以修改SQL和参数的值
                db.GetConnection(item.Key).Aop.OnExecutingChangeSql = OnExecutingChangeSql;
                //数据执行过滤
                db.GetConnection(item.Key).Aop.DataExecuting = DataExecuting;
                //查询后数据替换
                db.GetConnection(item.Key).Aop.DataExecuted = DataExecuted;
            }
        });

        Client.DbMaintenance.CreateDatabase();
        CodeFirst();
    }

    /// <summary>
    /// 数据库连接对象
    /// </summary>
    public SqlSugarScope Client { get; set; }

    /// <summary>
    /// 查询后数据替换
    /// </summary>
    /// <param name="value"></param>
    /// <param name="entity"></param>
    public virtual void DataExecuted(object value, DataAfterModel entity)
    { }

    /// <summary>
    /// 数据执行过滤
    /// <para>可用于新增或修改的时候，处理CreateName或UpdateName</para>
    /// </summary>
    /// <param name="OldValue"></param>
    /// <param name="entityInfo"></param>
    public virtual void DataExecuting(object OldValue, DataFilterModel entityInfo)
    {
        // 新增操作
        if (entityInfo.OperationType == DataFilterType.InsertByObject)
        {
            // 主键赋值
            if (entityInfo.EntityColumnInfo.IsPrimarykey && entityInfo.EntityColumnInfo.PropertyInfo.PropertyType == typeof(string))
            {
                if (entityInfo.PropertyName == "BillId" && ((dynamic)entityInfo.EntityValue).BillId == null)
                {
                    entityInfo.SetValue(Guid.NewGuid().ToString());
                }

                if (entityInfo.PropertyName == "DtlId" && ((dynamic)entityInfo.EntityValue).DtlId == null)
                {
                    entityInfo.SetValue(Guid.NewGuid().ToString());
                }
            }

            if (entityInfo.PropertyName == "CreateTime" && ((dynamic)entityInfo.EntityValue).CreateTime == null)
                entityInfo.SetValue(DateTime.Now);

            if (VampirewalCoreContext.GetInstance().GetContext("UserId", out object UserId))
            {
                if (entityInfo.PropertyName == "CreateUserId")
                {
                    var createUserId = ((dynamic)entityInfo.EntityValue).CreateUserId;
                    if (createUserId == null || createUserId == 0)
                        entityInfo.SetValue(UserId.ToString());
                }
            }

            if (VampirewalCoreContext.GetInstance().GetContext("UserName", out object UserName))
            {
                if (entityInfo.PropertyName == "CreateBy" && ((dynamic)entityInfo.EntityValue).CreateBy == null)
                    entityInfo.SetValue(UserName.ToString());
            }
        }

        // 更新操作
        if (entityInfo.OperationType == DataFilterType.UpdateByObject)
        {
            if (entityInfo.PropertyName == "UpdateTime")
                entityInfo.SetValue(DateTime.Now);

            if (VampirewalCoreContext.GetInstance().GetContext("UserId", out object UserId))
            {
                if (entityInfo.PropertyName == "UpdateUserId")
                    entityInfo.SetValue(UserId.ToString());
            }

            if (VampirewalCoreContext.GetInstance().GetContext("UserName", out object UserName))
            {
                if (entityInfo.PropertyName == "UpdateBy")
                    entityInfo.SetValue(UserName.ToString());
            }
        }
    }

    /// <summary>
    /// 配置Sqlsugar连接设置
    /// </summary>
    /// <param name="DbName"></param>
    /// <param name="ConnStr"></param>
    /// <param name="dbType"></param>
    /// <returns></returns>
    public virtual ConnectionConfig GetDbConnectionConfig(string DbName, string ConnStr, DBTypeEnum? dbType)
    {
        return new ConnectionConfig()
        {
            ConfigId = DbName,
            ConnectionString = ConnStr,//"Data Source=./demo.db",
            DbType = (SqlSugar.DbType)(int)dbType,
            IsAutoCloseConnection = true,
            InitKeyType = InitKeyType.Attribute,
            MoreSettings = new ConnMoreSettings()
            {
                IsWithNoLockQuery = true//看这里
            },
        };
    }

    /// <summary>
    /// SQL报错
    /// </summary>
    /// <param name="exp"></param>
    public virtual void OnError(SqlSugarException exp)
    {
    }

    /// <summary>
    /// 可以修改SQL和参数的值
    /// </summary>
    /// <param name="sql">sql=newsql</param>
    /// <param name="pars">foreach(var p in pars) //修改</param>
    /// <returns></returns>
    public virtual KeyValuePair<string, SugarParameter[]> OnExecutingChangeSql(string sql, SugarParameter[] pars)
    {
        return new KeyValuePair<string, SugarParameter[]>(sql, pars);
    }

    /// <summary>
    /// SQL执行完
    /// </summary>
    /// <param name="sql"></param>
    /// <param name="para"></param>
    public virtual void OnLogExecuted(string sql, SugarParameter[] para)
    {
    }

    /// <summary>
    /// SQL执行前
    /// </summary>
    /// <param name="sql"></param>
    /// <param name="para"></param>
    public virtual void OnLogExecuting(string sql, SugarParameter[] para)
    {
    }

    /// <summary>
    /// 创建表(需要建表的都需要重复写)
    /// <para>使用方法：CreateTable();</para>
    /// <para>这样一个表就能成功创建了</para>
    /// </summary>
    protected abstract void CodeFirst();

    /// <summary>
    /// 创建表，需写入CodeFirst中
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="length"></param>
    protected void CreateTable<T>(int length = 200) where T : TopModel
    {
        Client.CodeFirst.SetStringDefaultLength(length).InitTables(typeof(T));
    }

    /// <summary>
    /// 获取代码执行超过1秒的代码，放在OnLogExecuted
    /// </summary>
    /// <returns>超时sql所在信息</returns>
    protected string GetSqlExecuteTimeMoreOnceSecond()
    {
        double time = Client.Ado.SqlExecutionTime.TotalSeconds;

        if (time > 1)
        {
            //代码CS文件名
            var fileName = Client.Ado.SqlStackTrace.FirstFileName;
            //代码行数
            var fileLine = Client.Ado.SqlStackTrace.FirstLine;
            //方法名
            var FirstMethodName = Client.Ado.SqlStackTrace.FirstMethodName;
            //db.Ado.SqlStackTrace.MyStackTraceList[1].xxx 获取上层方法的信息

            return $"代码CS文件名：{fileName}-所在代码行数：{fileLine}-方法名：{FirstMethodName}(SQL执行时间：{time}秒)";
        }
        return "";
    }

}

/// <summary>
/// VampirewalCoreSqlSugar启动配置项
/// </summary>
public abstract class VampirewalCoreSqlSugarSetup : IVampirewalCoreSqlSugar
{


    /// <summary>
    /// 连接客户端
    /// </summary>
    protected SqlSugarScope Client { get; private set; }

    /// <inheritdoc/>
    public virtual void CodeFirst()
    {
    }

    /// <inheritdoc/>
    public virtual void DataExecuted(object value, DataAfterModel entity)
    {
    }

    /// <inheritdoc/>
    public virtual void DataExecuting(object OldValue, DataFilterModel entityInfo)
    {
        // 新增操作
        if (entityInfo.OperationType == DataFilterType.InsertByObject)
        {
            // 主键赋值
            if (entityInfo.EntityColumnInfo.IsPrimarykey && entityInfo.EntityColumnInfo.PropertyInfo.PropertyType == typeof(string))
            {
                if (entityInfo.PropertyName == "BillId" && ((dynamic)entityInfo.EntityValue).BillId == null)
                {
                    entityInfo.SetValue(Guid.NewGuid().ToString());
                }

                if (entityInfo.PropertyName == "DtlId" && ((dynamic)entityInfo.EntityValue).DtlId == null)
                {
                    entityInfo.SetValue(Guid.NewGuid().ToString());
                }
            }

            if (entityInfo.PropertyName == "CreateTime" && ((dynamic)entityInfo.EntityValue).CreateTime == null)
                entityInfo.SetValue(DateTime.Now);

            if (VampirewalCoreContext.GetInstance().GetContext("UserId", out object UserId))
            {
                if (entityInfo.PropertyName == "CreateUserId")
                {
                    var createUserId = ((dynamic)entityInfo.EntityValue).CreateUserId;
                    if (createUserId == null || createUserId == 0)
                        entityInfo.SetValue(UserId.ToString());
                }
            }

            if (VampirewalCoreContext.GetInstance().GetContext("UserName", out object UserName))
            {
                if (entityInfo.PropertyName == "CreateBy" && ((dynamic)entityInfo.EntityValue).CreateBy == null)
                    entityInfo.SetValue(UserName.ToString());
            }
        }

        // 更新操作
        if (entityInfo.OperationType == DataFilterType.UpdateByObject)
        {
            if (entityInfo.PropertyName == "UpdateTime")
                entityInfo.SetValue(DateTime.Now);

            if (VampirewalCoreContext.GetInstance().GetContext("UserId", out object UserId))
            {
                if (entityInfo.PropertyName == "UpdateUserId")
                    entityInfo.SetValue(UserId.ToString());
            }

            if (VampirewalCoreContext.GetInstance().GetContext("UserName", out object UserName))
            {
                if (entityInfo.PropertyName == "UpdateBy")
                    entityInfo.SetValue(UserName.ToString());
            }
        }
    }

    /// <inheritdoc/>
    public virtual Type[] FilterSugarTableType(Type[] types)
    {
        return types;
    }

    /// <inheritdoc/>

    public virtual ConnectionConfig GetDbConnectionConfig(string DbName, string ConnStr, DBTypeEnum? dbType)
    {
        return new ConnectionConfig()
        {
            ConfigId = DbName,
            ConnectionString = ConnStr,//"Data Source=./demo.db",
            DbType = (SqlSugar.DbType)(int)dbType,
            IsAutoCloseConnection = true,
            InitKeyType = InitKeyType.Attribute,
            MoreSettings = new ConnMoreSettings()
            {
                IsWithNoLockQuery = true//看这里
            },
        };
    }

    /// <inheritdoc/>

    public virtual string GetSqlExecuteTimeMoreOnceSecond()
    {
        double time = Client.Ado.SqlExecutionTime.TotalSeconds;

        if (time > 1)
        {
            //代码CS文件名
            var fileName = Client.Ado.SqlStackTrace.FirstFileName;
            //代码行数
            var fileLine = Client.Ado.SqlStackTrace.FirstLine;
            //方法名
            var FirstMethodName = Client.Ado.SqlStackTrace.FirstMethodName;
            //db.Ado.SqlStackTrace.MyStackTraceList[1].xxx 获取上层方法的信息

            return $"代码CS文件名：{fileName}-所在代码行数：{fileLine}-方法名：{FirstMethodName}(SQL执行时间：{time}秒)";
        }
        return "";
    }

    /// <inheritdoc/>

    public virtual void InitData()
    {
    }

    /// <inheritdoc/>

    public virtual void OnError(SqlSugarException exp)
    {
    }

    /// <inheritdoc/>

    public virtual KeyValuePair<string, SugarParameter[]> OnExecutingChangeSql(string sql, SugarParameter[] pars)
    {
        return new KeyValuePair<string, SugarParameter[]>(sql, pars);
    }

    /// <inheritdoc/>

    public virtual void OnLogExecuted(string sql, SugarParameter[] para)
    {
    }

    /// <inheritdoc/>

    public virtual void OnLogExecuting(string sql, SugarParameter[] para)
    {
    }

    /// <inheritdoc/>

    public void SetClient(ISqlSugarClient client)
    {
        Client = (SqlSugarScope)client;
    }

    /// <inheritdoc/>
    protected void CreateTable<T>(int length = 200) where T : TopModel
    {
        Client.CodeFirst.SetStringDefaultLength(length).InitTables(typeof(T));
    }
}

/// <summary>
/// SqlSugar 仓储实现类
/// </summary>
/// <typeparam name="TEntity"></typeparam>
public partial class SqlSugarRepository<TEntity>
where TEntity : class, new()
{
    private readonly string[] UpdateIgnoreColumns = new string[] { "CreatedTime", "CreatedUserId", "CreatedUserName" };

    #region 属性

    /// <summary>
    /// 初始化 SqlSugar 客户端
    /// </summary>
    private readonly SqlSugarScope _db;

    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="db"></param>
    public SqlSugarRepository(ISqlSugarClient db)
    {
        Context = _db = (SqlSugarScope)db;
        EntityContext = _db.GetConnectionScopeWithAttr<TEntity>();
        Ado = EntityContext.Ado;
    }

    /// <summary>
    /// 原生 Ado 对象
    /// </summary>
    public virtual IAdo Ado { get; }

    /// <summary>
    /// 数据库上下文
    /// </summary>
    public virtual SqlSugarScope Context { get; }

    /// <summary>
    /// 实体集合
    /// </summary>
    public virtual ISugarQueryable<TEntity> Entities => EntityContext.Queryable<TEntity>();

    /// <summary>
    /// 
    /// </summary>
    public virtual SqlSugarScopeProvider EntityContext { get; }

    #endregion

    #region 查询

    /// <summary>
    /// 检查是否存在
    /// </summary>
    /// <param name="whereExpression"></param>
    /// <returns></returns>
    public bool Any(Expression<Func<TEntity, bool>> whereExpression)
    {
        return Entities.Any(whereExpression);
    }

    /// <summary>
    /// 检查是否存在
    /// </summary>
    /// <param name="whereExpression"></param>
    /// <returns></returns>
    public async Task<bool> AnyAsync(Expression<Func<TEntity, bool>> whereExpression)
    {
        return await Entities.AnyAsync(whereExpression);
    }

    /// <summary>
    /// 获取总数
    /// </summary>
    /// <param name="whereExpression"></param>
    /// <returns></returns>
    public int Count(Expression<Func<TEntity, bool>> whereExpression)
    {
        return Entities.Count(whereExpression);
    }

    /// <summary>
    /// 获取总数
    /// </summary>
    /// <param name="whereExpression"></param>
    /// <returns></returns>
    public Task<int> CountAsync(Expression<Func<TEntity, bool>> whereExpression)
    {
        return Entities.CountAsync(whereExpression);
    }

    /// <summary>
    /// 获取一个实体
    /// </summary>
    /// <param name="whereExpression"></param>
    /// <returns></returns>
    public TEntity FirstOrDefault(Expression<Func<TEntity, bool>> whereExpression)
    {
        return Entities.First(whereExpression);
    }

    /// <summary>
    /// 获取一个实体
    /// </summary>
    /// <param name="whereExpression"></param>
    /// <returns></returns>
    public async Task<TEntity> FirstOrDefaultAsync(Expression<Func<TEntity, bool>> whereExpression)
    {
        return await Entities.FirstAsync(whereExpression);
    }

    /// <summary>
    /// 分页查询
    /// </summary>
    /// <param name="expression"></param>
    /// <param name="pageIndex"></param>
    /// <param name="pageSize"></param>
    /// <returns></returns>
    public (List<TEntity>, int) QueryableToPage(Expression<Func<TEntity, bool>> expression, int pageIndex = 0, int pageSize = 10)
    {
        int totalNumber = 0;
        var list = Entities.Where(expression).ToPageList(pageIndex, pageSize, ref totalNumber);
        return (list, totalNumber);
    }

    /// <summary>
    /// 分页查询
    /// </summary>
    /// <param name="expression"></param>
    /// <param name="order"></param>
    /// <param name="pageIndex"></param>
    /// <param name="pageSize"></param>
    /// <returns></returns>
    public (List<TEntity>, int) QueryableToPage(Expression<Func<TEntity, bool>> expression, string order, int pageIndex = 0, int pageSize = 10)
    {
        int totalNumber = 0;
        var list = Entities.Where(expression).OrderBy(order).ToPageList(pageIndex, pageSize, ref totalNumber);
        return (list, totalNumber);
    }

    /// <summary>
    /// 分页查询
    /// </summary>
    /// <param name="expression"></param>
    /// <param name="order"></param>
    /// <param name="ordertype"></param>
    /// <param name="pageIndex"></param>
    /// <param name="pageSize"></param>
    /// <param name="totalNumber"></param>
    /// <param name="totalPage"></param>
    /// <returns></returns>
    public List<TEntity> QueryableToPage(Expression<Func<TEntity, bool>> expression, Expression<Func<TEntity, object>> order, OrderByType ordertype, int pageIndex, int pageSize, ref int totalNumber, ref int totalPage)
    {
        return Entities.Where(expression).OrderByIF(order != null, order, ordertype).ToPageList(pageIndex, pageSize, ref totalNumber, ref totalPage);
    }

    /// <summary>
    /// 分页查询
    /// </summary>
    /// <param name="expression"></param>
    /// <param name="orderFiled"></param>
    /// <param name="orderBy"></param>
    /// <param name="pageIndex"></param>
    /// <param name="pageSize"></param>
    /// <returns></returns>
    public (List<TEntity>, int) QueryableToPage(Expression<Func<TEntity, bool>> expression, Expression<Func<TEntity, object>> orderFiled, string orderBy, int pageIndex = 0, int pageSize = 10)
    {
        int totalNumber = 0;

        if (orderBy.Equals("DESC", StringComparison.OrdinalIgnoreCase))
        {
            var list = Entities.Where(expression).OrderBy(orderFiled, OrderByType.Desc).ToPageList(pageIndex, pageSize, ref totalNumber);
            return (list, totalNumber);
        }
        else
        {
            var list = Entities.Where(expression).OrderBy(orderFiled, OrderByType.Asc).ToPageList(pageIndex, pageSize, ref totalNumber);
            return (list, totalNumber);
        }
    }

    /// <summary>
    /// 通过主键获取实体
    /// </summary>
    /// <param name="Id"></param>
    /// <returns></returns>
    public TEntity Single(dynamic Id)
    {
        return Entities.InSingle(Id);
    }

    /// <summary>
    /// 获取一个实体
    /// </summary>
    /// <param name="whereExpression"></param>
    /// <returns></returns>
    public TEntity Single(Expression<Func<TEntity, bool>> whereExpression)
    {
        return Entities.Single(whereExpression);
    }

    /// <summary>
    /// 通过排序获取一个实体
    /// </summary>
    /// <param name="whereExpression"></param>
    /// <param name="OrderExpression"></param>
    /// <param name="orderType"></param>
    /// <returns></returns>
    public TEntity OrderSingle(Expression<Func<TEntity, bool>> whereExpression, Expression<Func<TEntity, object>> OrderExpression, OrderByType orderType = OrderByType.Asc)
    {
        return Entities.OrderByIF(OrderExpression != null, OrderExpression, orderType).Single(whereExpression);
    }

    /// <summary>
    /// 获取一个实体
    /// </summary>
    /// <param name="whereExpression"></param>
    /// <returns></returns>
    public Task<TEntity> SingleAsync(Expression<Func<TEntity, bool>> whereExpression)
    {
        return Entities.SingleAsync(whereExpression);
    }

    /// <summary>
    /// 获取列表
    /// </summary>
    /// <returns></returns>
    public List<TEntity> ToList()
    {
        return Entities.ToList();
    }

    /// <summary>
    /// 获取列表
    /// </summary>
    /// <param name="whereExpression"></param>
    /// <returns></returns>
    public List<TEntity> ToList(Expression<Func<TEntity, bool>> whereExpression)
    {
        return Entities.Where(whereExpression).ToList();
    }

    /// <summary>
    /// 获取列表
    /// </summary>
    /// <param name="whereExpression"></param>
    /// <param name="orderByExpression"></param>
    /// <param name="orderByType"></param>
    /// <returns></returns>
    public List<TEntity> ToList(Expression<Func<TEntity, bool>> whereExpression, Expression<Func<TEntity, object>> orderByExpression = null, OrderByType orderByType = OrderByType.Asc)
    {
        return Entities.OrderByIF(orderByExpression != null, orderByExpression, orderByType).Where(whereExpression).ToList();
    }

    /// <summary>
    /// 获取列表
    /// </summary>
    /// <returns></returns>
    public Task<List<TEntity>> ToListAsync()
    {
        return Entities.ToListAsync();
    }

    /// <summary>
    /// 获取列表
    /// </summary>
    /// <param name="whereExpression"></param>
    /// <returns></returns>
    public Task<List<TEntity>> ToListAsync(Expression<Func<TEntity, bool>> whereExpression)
    {
        return Entities.Where(whereExpression).ToListAsync();
    }

    /// <summary>
    /// 获取列表
    /// </summary>
    /// <param name="whereExpression"></param>
    /// <param name="orderByExpression"></param>
    /// <param name="orderByType"></param>
    /// <returns></returns>
    public Task<List<TEntity>> ToListAsync(Expression<Func<TEntity, bool>> whereExpression, Expression<Func<TEntity, object>> orderByExpression = null, OrderByType orderByType = OrderByType.Asc)
    {
        return Entities.OrderByIF(orderByExpression != null, orderByExpression, orderByType).Where(whereExpression).ToListAsync();
    }

    #endregion

    #region 新增

    /// <summary>
    /// 
    /// </summary>
    /// <param name="entity"></param>
    /// <returns></returns>
    public virtual IInsertable<TEntity> AsInsertable(TEntity entity)
    {
        return EntityContext.Insertable(entity);
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="entities"></param>
    /// <returns></returns>
    public virtual IInsertable<TEntity> AsInsertable(params TEntity[] entities)
    {
        return EntityContext.Insertable(entities);
    }

    /// <summary>
    /// 新增一条记录
    /// </summary>
    /// <param name="entity"></param>
    /// <returns></returns>
    public virtual int Insert(TEntity entity)
    {
        return EntityContext.Insertable(entity).ExecuteCommand();
    }

    /// <summary>
    /// 新增多条记录
    /// </summary>
    /// <param name="entities"></param>
    /// <returns></returns>
    public virtual int Insert(params TEntity[] entities)
    {
        return EntityContext.Insertable(entities).ExecuteCommand();
    }

    /// <summary>
    /// 新增多条记录
    /// </summary>
    /// <param name="entities"></param>
    /// <returns></returns>
    public virtual int Insert(IEnumerable<TEntity> entities)
    {
        return EntityContext.Insertable(entities.ToArray()).ExecuteCommand();
    }

    /// <summary>
    /// 新增一条记录
    /// </summary>
    /// <param name="entity"></param>
    /// <returns></returns>
    public virtual Task<int> InsertAsync(TEntity entity)
    {
        return EntityContext.Insertable(entity).ExecuteCommandAsync();
    }

    /// <summary>
    /// 新增多条记录
    /// </summary>
    /// <param name="entities"></param>
    /// <returns></returns>
    public virtual Task<int> InsertAsync(params TEntity[] entities)
    {
        return EntityContext.Insertable(entities).ExecuteCommandAsync();
    }

    /// <summary>
    /// 新增多条记录
    /// </summary>
    /// <param name="entities"></param>
    /// <returns></returns>
    public virtual Task<int> InsertAsync(IEnumerable<TEntity> entities)
    {
        if (entities != null && entities.Any())
        {
            return EntityContext.Insertable(entities.ToArray()).ExecuteCommandAsync();
        }
        return Task.FromResult(0);
    }

    /// <summary>
    /// 新增一条记录返回实体
    /// </summary>
    /// <param name="entity"></param>
    /// <returns></returns>
    public virtual TEntity InsertReturnEntity(TEntity entity)
    {
        return EntityContext.Insertable(entity).ExecuteReturnEntity();
    }

    /// <summary>
    /// 新增一条记录返回实体
    /// </summary>
    /// <param name="entity"></param>
    /// <returns></returns>
    public virtual async Task<TEntity> InsertReturnEntityAsync(TEntity entity)
    {
        return await EntityContext.Insertable(entity).ExecuteReturnEntityAsync();
    }

    /// <summary>
    /// 新增一条记录返回自增Id
    /// </summary>
    /// <param name="insertObj"></param>
    /// <returns></returns>
    public virtual int InsertReturnIdentity(TEntity insertObj)
    {
        return EntityContext.Insertable(insertObj).ExecuteReturnIdentity();
    }

    /// <summary>
    /// 新增一条记录返回自增Id
    /// </summary>
    /// <param name="entity"></param>
    /// <returns></returns>
    public virtual async Task<long> InsertReturnIdentityAsync(TEntity entity)
    {
        return await EntityContext.Insertable(entity).ExecuteReturnBigIdentityAsync();
    }

    /// <summary>
    /// 新增一条记录返回雪花Id
    /// </summary>
    /// <param name="entity"></param>
    /// <returns></returns>
    public virtual long InsertReturnSnowflakeId(TEntity entity)
    {
        return EntityContext.Insertable(entity).ExecuteReturnSnowflakeId();
    }

    /// <summary>
    /// 新增一条记录返回雪花Id
    /// </summary>
    /// <param name="entity"></param>
    /// <returns></returns>
    public virtual async Task<long> InsertReturnSnowflakeIdAsync(TEntity entity)
    {
        return await EntityContext.Insertable(entity).ExecuteReturnSnowflakeIdAsync();
    }

    #endregion

    #region 更新

    /// <summary>
    /// 
    /// </summary>
    /// <param name="entity"></param>
    /// <returns></returns>
    public virtual IUpdateable<TEntity> AsUpdateable(TEntity entity)
    {
        return EntityContext.Updateable(entity).IgnoreColumns(UpdateIgnoreColumns);
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="entities"></param>
    /// <returns></returns>
    public virtual IUpdateable<TEntity> AsUpdateable(IEnumerable<TEntity> entities)
    {
        return EntityContext.Updateable<TEntity>(entities).IgnoreColumns(UpdateIgnoreColumns);
    }

    /// <summary>
    /// 更新一条记录
    /// </summary>
    /// <param name="entity"></param>
    /// <returns></returns>
    public virtual int Update(TEntity entity)
    {
        return EntityContext.Updateable(entity).IgnoreColumns(UpdateIgnoreColumns).ExecuteCommand();
    }

    /// <summary>
    /// 更新多条记录
    /// </summary>
    /// <param name="entities"></param>
    /// <returns></returns>
    public virtual int Update(params TEntity[] entities)
    {
        return EntityContext.Updateable(entities).IgnoreColumns(UpdateIgnoreColumns).ExecuteCommand();
    }

    /// <summary>
    /// 根据条件更新
    /// </summary>
    /// <param name="entity"></param>
    /// <param name="UpdateColumns"></param>
    /// <param name="WhereColumnNames"></param>
    /// <returns></returns>
    public virtual int Update(TEntity entity, Expression<Func<TEntity, object>> UpdateColumns = null, params string[] WhereColumnNames)
    {
        return EntityContext.Updateable(entity).WhereColumns(WhereColumnNames).UpdateColumnsIF(UpdateColumns != null, UpdateColumns).IgnoreColumns(UpdateIgnoreColumns).ExecuteCommand();
    }

    /// <summary>
    /// 更新多条记录
    /// </summary>
    /// <param name="entities"></param>
    /// <returns></returns>
    public virtual int Update(IEnumerable<TEntity> entities)
    {
        return EntityContext.Updateable(entities.ToArray()).IgnoreColumns(UpdateIgnoreColumns).ExecuteCommand();
    }

    /// <summary>
    /// 更新记录
    /// </summary>
    /// <param name="predicate">更新的条件</param>
    /// <param name="content">更新的内容</param>
    /// <returns></returns>
    public virtual int Update(Expression<Func<TEntity, bool>> predicate, Expression<Func<TEntity, TEntity>> content)
    {
        return EntityContext.Updateable(content).Where(predicate).IgnoreColumns(UpdateIgnoreColumns).ExecuteCommand();
    }

    /// <summary>
    /// 更新一条记录
    /// </summary>
    /// <param name="entity"></param>
    /// <returns></returns>
    public virtual async Task<int> UpdateAsync(TEntity entity)
    {
        return await EntityContext.Updateable(entity).IgnoreColumns(UpdateIgnoreColumns).ExecuteCommandAsync();
    }

    /// <summary>
    /// 更新记录
    /// </summary>
    /// <param name="predicate">更新的条件</param>
    /// <param name="content">更新的内容</param>
    /// <returns></returns>
    public virtual async Task<int> UpdateAsync(Expression<Func<TEntity, bool>> predicate, Expression<Func<TEntity, TEntity>> content)
    {
        return await EntityContext.Updateable(content).Where(predicate).IgnoreColumns(UpdateIgnoreColumns).ExecuteCommandAsync();
    }

    /// <summary>
    /// 更新多条记录
    /// </summary>
    /// <param name="entities"></param>
    /// <returns></returns>
    public virtual Task<int> UpdateAsync(params TEntity[] entities)
    {
        return EntityContext.Updateable(entities).IgnoreColumns(UpdateIgnoreColumns).ExecuteCommandAsync();
    }

    /// <summary>
    /// 更新多条记录
    /// </summary>
    /// <param name="entities"></param>
    /// <returns></returns>
    public virtual Task<int> UpdateAsync(IEnumerable<TEntity> entities)
    {
        return EntityContext.Updateable(entities.ToArray()).IgnoreColumns(UpdateIgnoreColumns).ExecuteCommandAsync();
    }

    #endregion

    #region 删除

    /// <summary>
    /// 删除一条记录
    /// </summary>
    /// <param name="entity"></param>
    /// <returns></returns>
    public virtual int Delete(TEntity entity)
    {
        return EntityContext.Deleteable(entity).ExecuteCommand();
    }

    /// <summary>
    /// 删除一条记录
    /// </summary>
    /// <param name="key"></param>
    /// <returns></returns>
    public virtual int Delete(object key)
    {
        return EntityContext.Deleteable<TEntity>().In(key).ExecuteCommand();
    }

    /// <summary>
    /// 删除多条记录
    /// </summary>
    /// <param name="keys"></param>
    /// <returns></returns>
    public virtual int Delete(params object[] keys)
    {
        return EntityContext.Deleteable<TEntity>().In(keys).ExecuteCommand();
    }

    /// <summary>
    /// 自定义条件删除记录
    /// </summary>
    /// <param name="whereExpression"></param>
    /// <returns></returns>
    public int Delete(Expression<Func<TEntity, bool>> whereExpression)
    {
        return EntityContext.Deleteable<TEntity>().Where(whereExpression).ExecuteCommand();
    }

    /// <summary>
    /// 删除一条记录
    /// </summary>
    /// <param name="entity"></param>
    /// <returns></returns>
    public virtual Task<int> DeleteAsync(TEntity entity)
    {
        return EntityContext.Deleteable(entity).ExecuteCommandAsync();
    }

    /// <summary>
    /// 删除一条记录
    /// </summary>
    /// <param name="key"></param>
    /// <returns></returns>
    public virtual Task<int> DeleteAsync(object key)
    {
        return EntityContext.Deleteable<TEntity>().In(key).ExecuteCommandAsync();
    }

    /// <summary>
    /// 删除多条记录
    /// </summary>
    /// <param name="keys"></param>
    /// <returns></returns>
    public virtual Task<int> DeleteAsync(params object[] keys)
    {
        return EntityContext.Deleteable<TEntity>().In(keys).ExecuteCommandAsync();
    }

    /// <summary>
    /// 自定义条件删除记录
    /// </summary>
    /// <param name="whereExpression"></param>
    /// <returns></returns>
    public async Task<int> DeleteAsync(Expression<Func<TEntity, bool>> whereExpression)
    {
        return await EntityContext.Deleteable<TEntity>().Where(whereExpression).ExecuteCommandAsync();
    }

    #endregion

    #region 其他

    /// <summary>
    /// 直接返回数据库结果
    /// </summary>
    /// <returns></returns>
    public virtual Task<List<TEntity>> AsAsyncEnumerable()
    {
        return AsQueryable().ToListAsync();
    }

    /// <summary>
    /// 直接返回数据库结果
    /// </summary>
    /// <param name="predicate"></param>
    /// <returns></returns>
    public virtual Task<List<TEntity>> AsAsyncEnumerable(Expression<Func<TEntity, bool>> predicate)
    {
        return AsQueryable(predicate).ToListAsync();
    }

    /// <summary>
    /// 直接返回数据库结果
    /// </summary>
    /// <returns></returns>
    public virtual List<TEntity> AsEnumerable()
    {
        return AsQueryable().ToList();
    }

    /// <summary>
    /// 直接返回数据库结果
    /// </summary>
    /// <param name="predicate"></param>
    /// <returns></returns>
    public virtual List<TEntity> AsEnumerable(Expression<Func<TEntity, bool>> predicate)
    {
        return AsQueryable(predicate).ToList();
    }

    /// <summary>
    /// 构建查询分析器
    /// </summary>
    /// <returns></returns>
    public virtual ISugarQueryable<TEntity> AsQueryable()
    {
        return Entities;
    }

    /// <summary>
    /// 构建查询分析器
    /// </summary>
    /// <param name="predicate"></param>
    /// <returns></returns>
    public virtual ISugarQueryable<TEntity> AsQueryable(Expression<Func<TEntity, bool>> predicate)
    {
        return Entities.Where(predicate);
    }

    /// <summary>
    /// 是否包含
    /// </summary>
    /// <param name="whereExpression"></param>
    /// <returns></returns>
    public virtual bool IsExists(Expression<Func<TEntity, bool>> whereExpression)
    {
        return Entities.Any(whereExpression);
    }

    /// <summary>
    /// 是否包含(异步)
    /// </summary>
    /// <param name="whereExpression"></param>
    /// <returns></returns>
    public virtual Task<bool> IsExistsAsync(Expression<Func<TEntity, bool>> whereExpression)
    {
        return Entities.AnyAsync(whereExpression);
    }

    /// <summary>
    /// 根据表达式查询多条记录
    /// </summary>
    /// <param name="predicate"></param>
    /// <returns></returns>
    public virtual ISugarQueryable<TEntity> Where(Expression<Func<TEntity, bool>> predicate)
    {
        return AsQueryable(predicate);
    }

    /// <summary>
    /// 根据表达式查询多条记录
    /// </summary>
    /// <param name="condition"></param>
    /// <param name="predicate"></param>
    /// <returns></returns>
    public virtual ISugarQueryable<TEntity> Where(bool condition, Expression<Func<TEntity, bool>> predicate)
    {
        return AsQueryable().WhereIF(condition, predicate);
    }

    #endregion

    #region 仓储事务

    /// <summary>
    /// 所有db开启事务
    /// </summary>
    public void BeginTran()
    {
        Context.BeginTran();
    }

    /// <summary>
    /// 所有db开启事务-异步
    /// </summary>
    /// <returns></returns>
    public async Task BeginTranAsync()
    {
        await Context.BeginTranAsync();
    }

    /// <summary>
    /// 切换仓储(注意使用环境)
    /// </summary>
    /// <typeparam name="T">实体类型</typeparam>
    /// <returns>仓储</returns>
    public virtual SqlSugarRepository<T> Change<T>()
        where T : class, new()
    {
        return VampirewalCoreContext.GetInstance().GetService<SqlSugarRepository<T>>();
    }

    /// <summary>
    /// 当前Client执行事务
    /// </summary>
    /// <param name="OperationAction"></param>
    /// <param name="ErrorAction"></param>
    /// <returns></returns>
    public bool ClientUseTran(Action OperationAction, Action<Exception> ErrorAction = null)
    {
        var result = Ado.UseTran(OperationAction, ErrorAction);

        return result.IsSuccess;
    }


    /// <summary>
    /// 所有db提交事务
    /// </summary>
    public void CommitTran()
    {
        Context.CommitTran();
    }

    /// <summary>
    /// 所有db提交事务-异步
    /// </summary>
    /// <returns></returns>
    public async Task CommitTranAsync()
    {
        await Context.CommitTranAsync();
    }

    /// <summary>
    /// 全局使用事务
    /// </summary>
    /// <param name="OperationAction"></param>
    /// <param name="ErrorAction"></param>
    /// <returns></returns>
    public bool ContextUseTran(Action OperationAction, Action<Exception> ErrorAction = null)
    {
        var result = Context.Ado.UseTran(OperationAction, ErrorAction);
        return result.IsSuccess;
    }

    /// <summary>
    /// 当前db开启事务
    /// </summary>
    public void CurrentBeginTran()
    {
        Ado.BeginTran();
    }

    /// <summary>
    /// 当前db开启事务-异步
    /// </summary>
    /// <returns></returns>
    public async Task CurrentBeginTranAsync()
    {
        await Ado.BeginTranAsync();
    }


    /// <summary>
    /// 当前db提交事务
    /// </summary>
    public void CurrentCommitTran()
    {
        Ado.CommitTran();
    }

    /// <summary>
    /// 当前db提交事务-异步
    /// </summary>
    /// <returns></returns>
    public async Task CurrentCommitTranAsync()
    {
        await Ado.CommitTranAsync();
    }

    /// <summary>
    /// 当前db回滚事务
    /// </summary>
    public void CurrentRollbackTran()
    {
        Ado.RollbackTran();
    }

    /// <summary>
    /// 当前db回滚事务-异步
    /// </summary>
    /// <returns></returns>
    public async Task CurrentRollbackTranAsync()
    {
        await Ado.RollbackTranAsync();
    }

    /// <summary>
    /// 所有db回滚事务
    /// </summary>
    public void RollbackTran()
    {
        Context.RollbackTran();
    }

    /// <summary>
    /// 所有db回滚事务-异步
    /// </summary>
    /// <returns></returns>
    public async Task RollbackTranAsync()
    {
        await Context.RollbackTranAsync();
    }

    #endregion
}